﻿using System.Collections.ObjectModel;
using BusinessObjects;
using MainGameModule.Models;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using YourWorld.Common;

namespace MainGameModule.ViewModels
{
    public class ChatViewModel : ViewModelBase
    {
        private IRegionManager regionManager;
        private IUnityContainer container;
        private IGameModel gameModel;

        private GameMainViewModel mainGameViewModel;

        private ObservableCollection<ChatMessage> messages;
        private string name;

        public ObservableCollection<ChatMessage> Messages
        {
            get
            {
                if (this.messages == null)
                    this.messages = new ObservableCollection<ChatMessage>();

                return this.messages;
            }
            set
            {
                if (this.messages == value)
                    return;

                this.messages = value;
                this.NotifyPropertyChanged("Messages");
            }
        }

        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (this.name == value)
                    return;

                this.name = value;
                this.NotifyPropertyChanged("Name");
            }
        }

        public GameMainViewModel MainGameViewModel
        {
            get
            {
                return this.mainGameViewModel;
            }
            set
            {
                if (this.mainGameViewModel == value)
                    return;

                this.mainGameViewModel = value;
                this.NotifyPropertyChanged("MainGameViewModel");
            }
        }

        public ChatViewModel( IRegionManager regionManager, IUnityContainer container, IGameModel gameModel )
        {
            this.regionManager = regionManager;
            this.container = container;
            this.gameModel = gameModel;

            this.mainGameViewModel = this.container.Resolve<GameMainViewModel>();
            this.gameModel.ChatMessageReceived += this.MessageReceived;
            //this.Name = this.mainGameViewModel.Player.Name;
        }

        public void SendChatMessage( string text )
        {
            ChatMessage message = new ChatMessage()
            {
                SenderId = this.mainGameViewModel.Player.Id,
                SenderMapId = this.mainGameViewModel.Game.MapId,
                SenderName = this.mainGameViewModel.Player.Name,
                Text = text
            };

            this.gameModel.SendChatMessage( message );
        }

        private void MessageReceived( ChatMessage message )
        {
            this.Messages.Add( message );
        }
    }
}